﻿import sys
import xbmc
import xbmcgui
import xbmcplugin
import xbmcvfs
import socket
import xbmcaddon
import cookielib
import urllib2
import simplejson as json

settings = xbmcaddon.Addon(id='script.module.twitch_notifications')
language = settings.getLocalizedString
addon_id      = settings.getAddonInfo('id')
path     = xbmc.translatePath( settings.getAddonInfo('path') )
UA = 'Android 4.3.0'

def GET(target, post=None):
    try:
        req = urllib2.Request(url = target, data = post, headers = {'User-Agent':UA})
        resp = urllib2.urlopen(req)
        CE = resp.headers.get('content-encoding')
        http = resp.read()
        resp.close()
        return http
    except Exception, e:
        xbmc.log( '[%s]: GET EXCEPT [%s]' % (addon_id, e), 4 )
        showMessage('HTTP ERROR', e, 5000)
        
def showMessage(heading, message, times = 3000, pics = ''):
    try: xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")' % (heading.encode('utf-8'), message.encode('utf-8'), times, pics.encode('utf-8')))
    except Exception, e:
        xbmc.log( '[%s]: showMessage: Transcoding UTF-8 failed [%s]' % (addon_id, e), 2 )
        try: xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")' % (heading, message, times, pics))
        except Exception, e:
            xbmc.log( '[%s]: showMessage: exec failed [%s]' % (addon_id, e), 3 )
            
class WASEngine(xbmcgui.WindowXMLDialog):
    def __init__(self, strXMLname, strFallbackPath, strDefaultName, forceFallback = True):
        self.url=''
        self.user=''
        self.game=''
        self.stat=''
    def onInit(self):

        self.controls = {}
        self.label = self.getControl(2002)
        self.label.setLabel(self.stat)
        self.label = self.getControl(2003)
        self.label.setLabel(self.user)
        self.label = self.getControl(2004)
        self.label.setLabel(self.game)
        self.img=self.getControl(2005)
        self.img.setImage(path+'/icon.png')

    def updater(self,url,user,game):
        self.label = self.getControl(2004)
        self.label.setLabel(game)
        self.label = self.getControl(2003)
        self.label.setLabel(user)

def checkname(name):

    res = 'any'
    name=name
    url1 = 'http://usher.justin.tv/find/'+name+'.json?type=live'
    url = 'http://usher.justin.tv/find/' + name + '.json?type=' + res + '&private_code=null&group='
    data = json.loads(GET(url1))
    if data == []:
        #showMessage('Twitch.TV','Стрим не найден')
        return None
    try: game= data[0]['meta_game']
    except: game= 'No Game'
    return {'name':name,'game':game}

def show_not(name,game):
    ui = WASEngine("DialogDownloadProgress.xml", path, "Default")
    url='https://api.twitch.tv/kraken/channels/%s'%name
    data = json.loads(GET(url))
    ui.stat=data['status']
    ui.user=name
    ui.game=game
    ui.show()
    xbmc.sleep(3000)
    ui.close()

def get_data():
    cnames=settings.getSetting("customstr").split(',')
    subs=settings.getSetting("tuser")
    link='https://api.twitch.tv/kraken/users/%s/follows/channels'%subs
    http = GET(link)
    json1=json.loads(http)
    names=[]

    for g in json1['follows']:
        names.append( g['channel']['name'])
        
    fnames=names
    check={}
    if int(settings.getSetting("cmode"))==0:
        names=fnames+cnames
    if int(settings.getSetting("cmode"))==1:
        names=fnames
    if int(settings.getSetting("cmode"))==2:
        names=cnames

    for c in names:
        check[c]=0
    
    return {'names':names, 'check':check}

while not xbmc.abortRequested:

    if settings.getSetting("started")=='true':
        try:
            data=get_data()
            names=data['names']
            check=data['check']
            print data
            for t in names:
                
                out=checkname(t)
                if out and check[t]==0:
                    check[t]=1
                    show_not(out['name'],out['game'])
                else: check[t]=0
            tick=360
            while(tick>0 and not xbmc.abortRequested):
                xbmc.sleep(1000)
                tick=tick-1
        except:
            print 'TN: get data fail'
    else: xbmc.sleep(1000)
